package com.file.parser;

import com.file.bo.OverseasDiploma;
import com.file.bo.ResponseData;
import com.file.constant.ErrorCode;
import com.file.util.JsonUtils;
import com.google.common.base.Splitter;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 国外学历
 * @author anyspa
 */

@Slf4j
public class CscseHtmlParser {

    public ResponseData<String> parseCscseHtmlToJson(String daId, String filePath) {
        log.info("parseCscseHtmlToJson started, daId:{}", daId);
        String json = null;

        try {
            OverseasDiploma diploma = parseCscseHtml(filePath);
            json = JsonUtils.convertObjectToJson(diploma);
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseXlcxHtmlToJson failed", e);
            return new ResponseData<>(json, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
                    ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseCscseHtmlToJson completed, daId:{}, json:{}", daId, json);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private OverseasDiploma parseCscseHtml(String filePath) throws IOException {
        File input = new File(filePath);
        OverseasDiploma overseasDiploma = new OverseasDiploma();

        Document doc = Jsoup.parse(input, "UTF-8");

        overseasDiploma.setCertificateNo(doc.getElementById("number").html());
        List<String> firstpStrList =
                Splitter.on("，").trimResults().splitToList(doc.getElementById("firstp").html());

        String name = firstpStrList.get(0).substring(firstpStrList.get(0).lastIndexOf("&nbsp;") + 6).trim();
        overseasDiploma.setName(name);
        overseasDiploma.setSex(firstpStrList.get(1));

        String nationality = firstpStrList.get(2).substring(0, firstpStrList.get(2).indexOf("国籍"));
        overseasDiploma.setNationality(nationality);

        overseasDiploma.setBirthDate("");
        overseasDiploma.setBirthPlace("");
        String birthDateAndPlaceStr = firstpStrList.get(3);
        // 250328：正则提取生日（如有）
        String birthDateRegex = "(\\d{4})年(\\d{1,2})月(\\d{1,2})日";
        Pattern birthDatePattern = Pattern.compile(birthDateRegex);
        Matcher birthDateMatcher = birthDatePattern.matcher(birthDateAndPlaceStr);
        String birthDateStr = "";
        if (birthDateMatcher.find()) {
            birthDateStr = birthDateMatcher.group();
            overseasDiploma.setBirthDate(birthDateStr);
        }
        // 250328：正则提取出生地（如有）
        String birthPlaceRegex = "生于([^。]+)。";
        Pattern birthPlacePattern = Pattern.compile(birthPlaceRegex);
        Matcher birthPlaceMatcher = birthPlacePattern.matcher(birthDateAndPlaceStr);
        if (birthPlaceMatcher.find()) {
            String birthPlaceStr = birthPlaceMatcher.group(1);
            // 去除日期和出生地一样的case
            Matcher birthPlaceMatcherNew = birthDatePattern.matcher(birthPlaceStr);
            if (!birthPlaceMatcherNew.find() && !StringUtils.equals(birthPlaceStr, birthDateStr)) {
                overseasDiploma.setBirthPlace(birthPlaceStr);
            }
        }

        String secondpStr = doc.getElementById("secondp").html();
        Pattern datePattern = Pattern.compile("[0-9]{4}年[0-9]{1,2}月");
        Matcher dateMatcher = datePattern.matcher(secondpStr);
        List<String> dateList = new ArrayList<>();
        while (dateMatcher.find()) {
            dateList.add(dateMatcher.group());
        }
        if (dateList.size() == 1) {
            overseasDiploma.setDateOfEnrollment("");
            overseasDiploma.setDateOfCertificateIssuance(dateList.get(0));
        } else if (dateList.size() >= 2) {
            overseasDiploma.setDateOfEnrollment(dateList.get(0));
            overseasDiploma.setDateOfCertificateIssuance(dateList.get(dateList.size() - 1));
        }

        String major = "";
        String academicDegree = "";
        if (secondpStr.contains("专业领域为")) {
            major = secondpStr.substring(secondpStr.indexOf("专业领域为") + 5, secondpStr.lastIndexOf("。"));
        } else {
            Pattern majorPattern = Pattern.compile("学习\\S{2,20}专业");
            Matcher majorMatcher = majorPattern.matcher(secondpStr);
            if (majorMatcher.find()) {
                major = majorMatcher.group().substring(2, majorMatcher.group().length() - 2);
            }
        }
        overseasDiploma.setMajor(major);

        Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]{4}学位");
        Matcher matcher = pattern.matcher(secondpStr);
        if (matcher.find()) {
            academicDegree = matcher.group().substring(0, 4);
        }
        // 250320: 超过四个字的学位，再额外解析一遍
        String academicDegreeNew = "";
        String startTag = "授予的";
        String endTag = "学位";
        int start = secondpStr.indexOf(startTag) + startTag.length();
        int end = secondpStr.indexOf(endTag, start);
        if (secondpStr.contains(startTag) && start > 6 && end != -1 && start < end) {
            academicDegreeNew = secondpStr.substring(start, end);
            if (!StringUtils.isEmpty(academicDegreeNew) && !academicDegree.equals(academicDegreeNew)) {
                academicDegree = academicDegreeNew;
            }
        }
        // 250320：学位前后为“颁发的”。优先级最低
        String academicDegreeNew2 = "";
        String startTag2 = "颁发的";
        String endTag2 = endTag;
        int start2 = secondpStr.indexOf(startTag2) + startTag2.length();
        int end2 = secondpStr.indexOf(endTag2, start2);
        if (secondpStr.contains(startTag2) && start2 > 6 && end2 != -1 && start2 < end2) {
            academicDegreeNew2 = secondpStr.substring(start2, end2);
            if (!StringUtils.isEmpty(academicDegreeNew2) && !academicDegree.equals(academicDegreeNew2) && !academicDegreeNew.equals(academicDegreeNew2)) {
                academicDegree = academicDegreeNew2;
            }
        }

        // 250328：学位前后为“被授予”“学位”
        String academicDegree3 = "";
        String startTag3 = "被授予";
        String endTag3 = "学位";
        int start3 = secondpStr.indexOf(startTag3) + startTag3.length();
        int end3 = secondpStr.indexOf(endTag3, start3);
        if (secondpStr.contains(startTag3) && start3 > 6 && end3 != -1 && start3 < end3) {
            academicDegree3 = secondpStr.substring(start3, end3);
            if (!StringUtils.isEmpty(academicDegree3) && !academicDegree.equals(academicDegree3) && !academicDegreeNew.equals(academicDegree3)) {
                academicDegree = academicDegree3;
            }
        }
        overseasDiploma.setAcademicDegree(academicDegree);

        // 处理毕业院校
        int graduateSchoolStartTag = secondpStr.indexOf("在") + 1;
        int graduateSchoolEndTag = secondpStr.indexOf("（");
        if (graduateSchoolEndTag == -1) {
            graduateSchoolEndTag = secondpStr.indexOf("(");
            if (graduateSchoolEndTag == -1) {
                graduateSchoolEndTag = secondpStr.indexOf("学习");
            }
        }
        String graduateSchool = secondpStr.substring(graduateSchoolStartTag, graduateSchoolEndTag);
        if (graduateSchool.contains("，")) {
            String text = graduateSchool.split("，")[1];
            graduateSchool = text.substring(text.indexOf("在") + 1);
        }
        overseasDiploma.setGraduateSchool(graduateSchool);

        try {
            String dateOfAuthentication = doc.getElementById("certificatedate").html();
            overseasDiploma.setDateOfAuthentication(dateOfAuthentication);
        } catch (Exception e) {
            overseasDiploma.setDateOfAuthentication("");
        }

        log.info("overseasDiploma:{}", overseasDiploma);

        return overseasDiploma;
    }

    public static void main(String[] args) {
        CscseHtmlParser cscseHtmlParser = new CscseHtmlParser();
        String json = "";
        json = cscseHtmlParser.parseCscseHtmlToJson("", "D:\\data\\file\\cscse\\cscse_xlzm1.html").getData();
        System.out.println(json);
        json = cscseHtmlParser.parseCscseHtmlToJson("", "D:\\data\\file\\cscse\\cscse_xlzm2.html").getData();
        System.out.println(json);
        json = cscseHtmlParser.parseCscseHtmlToJson("", "D:\\data\\file\\cscse\\cscse_xlzm3.html").getData();
        System.out.println(json);
        json = cscseHtmlParser.parseCscseHtmlToJson("", "D:\\data\\file\\cscse\\cscse_xlzm4.html").getData();
        System.out.println(json);
        json = cscseHtmlParser.parseCscseHtmlToJson("", "D:\\data\\file\\cscse\\cscse_xlzm6.html").getData();
        System.out.println(json);
        json = cscseHtmlParser.parseCscseHtmlToJson("", "D:\\data\\file\\cscse\\cscse_xlzm7.html").getData();
        System.out.println(json);
        json = cscseHtmlParser.parseCscseHtmlToJson("", "D:\\data\\file\\cscse\\cscse_xlzm8.html").getData();
        System.out.println(json);

    }

}
